<?php
/* 
    Name：FastPHP
    CopyRight: Mr.Fu 2019SR0832915
*/
namespace app\base;
/*
	 全局通用文件上传模块 
	 Author:FastPHP
*/
use \app\base\Common;
use \app\extend\upload\Uploader;

class Upload extends Common
{
	public function _initialize(){
    	//执行父类的构造方法
    	parent::_initialize();
    }
    public function upload_do()
    {
		//定义基本上传文件类型
	    $file_type=array(
	    	'image'		=>'images',
	    	'face'		=>'facepic',
	    	'file'		=>'files',
	    	'audio'		=>'audio',
	    	'video'		=>'video'
        );
        //获取上传文件类型
        $type=input('type')??'image';
        //获取上传文件是否压缩
		$Compress=input('Compress')??0;
        
        //读取各种类型文件的上传限制
		if($type=='image' || $type=='face'){
			//读取图片类型的设置
			$allowExts=explode(',',$this->Config['attach_format_image']);
			$maxSize=GetSizeToBit($this->Config['attach_format_image_size']);
		}else if($type=='video'){
			//读取视频类型的设置
			$allowExts=explode(',',$this->Config['attach_format_video']);
			$maxSize=GetSizeToBit($this->Config['attach_format_video_size']);
		}else if($type=='audio'){
			//读取音频类型的设置
			$allowExts=explode(',',$this->Config['attach_format_audio']);
			$maxSize=GetSizeToBit($this->Config['attach_format_audio_size']);
		}else{
			//读取其它类型的设置
			$allowExts=explode(',',$this->Config['attach_format_file']);
			$maxSize=GetSizeToBit($this->Config['attach_format_file_size']);
		}
	    $upload 			= new Uploader();// 实例化上传类
	    $upload->maxSize 	= $maxSize;
	    $upload->allowExts 	= $allowExts;
	    $upload->supportMulti 	= true;
	    
	    if(isset($file_type[$type])){
	    	$type_dir=$file_type[$type];
	    }else{
	    	$type_dir="other";
	    }
		
	    $dir				= 'uploads'.DS.$type_dir.DS.date('Ymd',time()).DS;
	    $upload->savePath 	= ROOT_PATH.$dir;// 设置附件
	    $upload->saveRule 	= time().GetRandStr(10);
	    
	    if(!$upload->upload()) {
	    	// 上传错误提示错误信息
	        $errormsg 	= $upload->getErrorMsg();
	        $arr 		=  array(
	            'status'	=>1,
	            //返回状态
	            'error'		=>$errormsg,
	            //返回错误
	        );
	        return $arr;
	    }else{
	    	// 上传成功 获取上传文件信息
			$info 				= $upload->getUploadFileInfo();
			$data=array();
			//判断图片压缩
			if(($type=='image' || $type=='face') && ($Compress==1)){
				foreach($info as $file){
					//开始格式转换-所有图片转换成JPG,并清理源文件
					$result=\app\base\Image::convert($file['savepath'].$file['savename'],'','jpg',true);
					//开始压缩JPG
					\app\base\Image::ImageCompress($result);
					str_replace(ROOT_PATH,'',$file['savepath']).$file['savename'];
					$imgurl=str_replace(ROOT_PATH,'',$result);
					$data[]=DS.$imgurl;
				}
			}else{
				foreach($info as $file){
					$imgurl=str_replace(ROOT_PATH,'',$file['savepath']).$file['savename'];
					$data[]=DS.$imgurl;
				}
			}
	        $info2['data']	= $data;
	        $info2['status']= 0;
	        return $info2;        
	    }
    }
}
